package debang

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"orderApi/express"
	"strconv"
	"strings"
	"time"
)

// DbRoutesPost 德邦快递路由查询
func DbRoutesPost(appkey, params, companyCode string) (benXiRoutes express.BenXiRoutes) {
	benXiRoutes.Status = true
	dUrl := "http://dpapi.deppon.com/dop-interface-sync/standard-query/newTraceQuery.action"

	// 时间戳
	timestamp := strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
	// timestamp := "1656315176172"

	// 密文摘要
	digest := digest(params, appkey, timestamp)
	// 请求头Body设置
	values := url.Values{}
	values.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
	values.Add("params", params)           // 请求参数
	values.Add("digest", digest)           // (密文摘要
	values.Add("timestamp", timestamp)     // 时间戳
	values.Add("companyCode", companyCode) // 第三方接入商的公司编码，双安约定

	form, err := http.PostForm(dUrl, values)
	if err != nil {
		benXiRoutes.Status = false
		benXiRoutes.Message = fmt.Sprintf("%v", err)
		return benXiRoutes
	}

	// defer form.Body.Close()
	all, err := ioutil.ReadAll(form.Body)
	fmt.Println(string(all))
	if err != nil {
		benXiRoutes.Status = false
		benXiRoutes.Message = fmt.Sprintf("%v", err)
		return benXiRoutes
	}
	db := new(DbRoutes)
	json.Unmarshal(all, db)
	marshal, _ := xml.Marshal(db.ResponseParam)
	xml.Unmarshal(marshal, &benXiRoutes)
	return benXiRoutes
}

//  digest 密文摘要
func digest(params, appkey, timestamp string) string {

	// 拼接字符串
	digest := strings.Join([]string{params, appkey, timestamp}, "")

	h := md5.New()
	h.Write([]byte(digest))

	return base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(h.Sum(nil))))
}
